﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Ixyu.Controllers;
using Ixyu.Dtos;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;

namespace Ixyu.Web.Host.Controllers
{
    public class FileController : IxyuControllerBase
    {
        private IHostingEnvironment host;

        public FileController(IHostingEnvironment env)
        {
            host = env;
        }
        public JsonResult Upload(IList<IFormFile> files)
        {
            var path = host.WebRootPath + $@"\uploads";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var list = new List<FileDto>();
            foreach (var file in files)
            {
                var filename = Guid.NewGuid().ToString("N")+"-" + file.FileName;
                var fullName = path + "/" + filename;
                using (FileStream fs = System.IO.File.Create(fullName))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
                list.Add(new FileDto()
                {
                    Name = file.FileName,
                    Url = "/uploads/" + filename
                });
            }
            return Json(list);
        }
    }

    
}